package packaged;

import models.sys.Token;
import play.libs.Time;

import java.util.List;

public class TokenManager {


    public static boolean recordToken(String tokenStr, String flag, String value, String overtime, int type) {

//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(new Date());
//        calendar.add(Calendar.SECOND, Time.parseDuration(overtime));

        switch (type) {
            case Token.Type.LOGIN_REMEMBER:
                List<Token> tokens = Token.find("flag = ? AND value = ? AND type = ? AND overtime > now() ORDER BY overtime",flag,value,type).fetch();
                if (tokens.size() > 0) {
                    Token token = tokens.remove(0);
                    for (Token tk : tokens) {
                        tk.delete();
                    }
                    token.overtime = Time.parseCRONExpression(overtime);
                    return token.save() != null;
                }
        }

        Token token = new Token();
        token.token = tokenStr;
        token.flag = flag;
        token.value = value;
        token.overtime = Time.parseCRONExpression(overtime);
        token.type = type;
        return token.save() != null;
    }
}
